import { Box, Button, TextField } from "@mui/material";
import { useState } from "react";
import { startSession } from "../session";
import { useGetAccountMutation } from "../api/invest";

export const HelloPage = () => {
  const [token, setToken] = useState("");
  const [getAccount, { isLoading, data, isError }] = useGetAccountMutation();
  const onHandleClick = async () => {
    try {
        await getAccount(token).unwrap();
    } catch(e) {
        alert("Неверный токен")
    }
  };

  if (data) {
    const id = data.accounts[0].id;
    console.log(data);
    startSession(token, id);
    location.reload();
  }

  return (
    <Box sx={{width: "40%", margin: "0 auto"}}>
      <Box sx={{ textAlign: "left" }}>
        <div className="hello__title">Введите API-ключ тинькофф инвестиций</div>
        <a
          href="https://www.tinkoff.ru/invest/open-api/"
          className="hello__link"
          target="blank"
        >
          Что это?
        </a>
      </Box>
      <TextField
        id="standard-basic"
        label="Api-ключ"
        variant="standard"
        sx={{ width: "100%", marginBottom: "20px" }}
        onChange={(e) => setToken(e.target.value)}
      />
      <Button
        variant="contained"
        sx={{ display: "block", textAlign: "center" }}
        onClick={() => onHandleClick()}
      >
        Войти
      </Button>
    </Box>
  );
};
